package com.education.service.oss.controller.admin;

import com.education.exception.OnlineEducationException;
import com.education.result.R;
import com.education.result.ResultCodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import com.education.service.oss.service.FileService;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * 文件上传控制器 [ 生产者 ]
 * Created by Lance on 2020/06/23 18:07
 */
@Api(tags = "阿里云文件管理")
@Slf4j
@RestController
@RequestMapping("/admin/oss/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @ApiOperation("文件上传")
    @PostMapping("upload")
    public R upload(@ApiParam(value = "文件", required = true) @RequestParam("file") MultipartFile file,
                    @ApiParam(value = "模块", required = true) @RequestParam("model") String model) {
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            // 文件 url 地址
            String uploadUrl = fileService.upload(inputStream, model, originalFilename);

            return R.ok().data("uploadUrl", uploadUrl).message("文件上传成功!");
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            throw new OnlineEducationException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }

    }

    /**
     * 测试  OpenFeign的使用
     *
     * @return
     */
    @ApiOperation(value = "测试")
    @GetMapping("test")
    public R test() {
        log.info("微服务中的 OSS Test 方法开始被调用 !!");
//        try {
//            // 让程序睡3秒 , 模拟测试超时操作
//            TimeUnit.SECONDS.sleep(3);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        log.info("微服务中的 OSS Test 方法被调用完毕 !!");
        return R.ok();
    }

    /**
     * 删除头像的控制器
     *
     * @param url
     * @return
     */
    @ApiOperation("删除阿里云服务器头像")
    @DeleteMapping("remove")
    public R removeFile(@ApiParam(value = "输入要删除文件的URL地址", required = true) @RequestBody String url) {
        fileService.removeFile(url);
        return R.ok().message("头像删除成功!!");
    }
}
